import { app } from 'electron'
import path from 'path'
import { DataSource } from 'typeorm'
import { is } from '@electron-toolkit/utils'

// 引入表
import { User } from './entity/User'
import { Frequency } from './entity/Frequency'
import { Answer } from './entity/Answer'
import { Message } from './entity/Message'

let database = is.dev ? 'database.db' : path.join(app.getPath('userData'), 'database.db')

// 数据库连接的文件
export const dataSource = new DataSource({
  type: 'sqlite',
  database,
  synchronize: true,
  entities: [User, Frequency, Answer, Message], //每增加一个表都要导入一次
  logging: ['error']
})
export const manager = dataSource.manager
export const initDataBase = () => {
  dataSource
    .initialize()
    .then(() => {
      console.log('Data Source has been initialized!')
    })
    .catch((err) => {
      console.error('Error during Data Source initialization', err)
    })
}

export const destroyDataBase = () => {
  dataSource.destroy()
}
